#!/usr/bin/env bash
set -e
set -u

write_omniverse_toml() {
  # Write out an omniverse.toml configuration file for Kit that contains a bookmark
  # for a custom provided nucleus server.
  local nucleus_server=$$1
  mkdir --parents /home/ubuntu/.nvidia-omniverse/config
  cat <<EOF > /home/ubuntu/.nvidia-omniverse/config/omniverse.toml
[bookmarks]
"$${nucleus_server}" = "omniverse://$${nucleus_server}"
EOF
}


USER_ID="$${USER_ID:-""}"
if [ -z "$${USER_ID}" ]; then
  echo "User id is not set"
fi

# if NVDA_KIT_NUCLEUS is set, write out the omniverse.toml value
if [ -n "$${NVDA_KIT_NUCLEUS:-}" ]; then
  write_omniverse_toml "$${NVDA_KIT_NUCLEUS}"
  # Additionally set the Nucleus server address to the provided address.
  nucleus_cmd="--/ovc/nucleus/server=$${NVDA_KIT_NUCLEUS}"
fi

CMD="/app/kit/kit"
ARGS=(
"/app/apps/$KIT_FILE_NAME_BREADCRUMB"
$KIT_ARGS_BREADCRUMB
$${NVDA_KIT_ARGS:-""}
$${nucleus_cmd:-""}
)

# Emit the .kit file to be executed if kit_verbose is set
# This prevents potentially dumping a sensitive file to a logfile
if [ $${OM_KIT_VERBOSE:-0} = "1" ]; then
  export KIT_FILE=/app/apps/$KIT_FILE_NAME_BREADCRUMB
  echo "==== Print out kit config $${KIT_FILE} for debugging ===="
  cat $${KIT_FILE}
  echo "==== End of kit config $${KIT_FILE} ===="
fi

echo "Starting Kit with $$CMD $${ARGS[@]} $$@"

# Chown the Kit caching directories to avoid permissions
# issues between root and ubuntu user.
chown -R ubuntu:ubuntu /home/ubuntu/.cache/ov
chown -R ubuntu:ubuntu /home/ubuntu/.local/share/ov

eval "$$CMD" "$${ARGS[@]}" "$$@"
